<?php

class UploadController extends Controller
{
	public $layout='//layouts/column1';

	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('novoUpload'),
				'users'=>array('*'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('meusUploads'),
				'users'=>array('*'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('delete'),
				'users'=>array('*'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	public function actionNovoUpload()
	{
		$model=new Upload;
		$model->unsetAttributes();
		$model->id_usuario_fk = Usuario::getUsuario()->id_usuario;
		$model->data = date("Y-m-d");
		$model->excluido = 0;
		$model->arquivos = array(new Arquivo);
		
		$files = CUploadedFile::getInstancesByName('arquivos');
		
		if (isset($_POST["yt0"]))
		{
			$model->attributes=$_POST['Upload'];
			
			if (count($files) > 0)
			{
				if ($this->ValidaArquivos($files))
				{
					if ($model->save())
					{
						$caminho = Yii::getPathOfAlias('webroot') . "/files/" . $model->id_upload;
						$this->CriarPasta($caminho);
						
						foreach ($files as $file)
						{
							$arquivo = new Arquivo;
							$arquivo->unsetAttributes();
							$arquivo->nome = $file->name;
							$arquivo->local = "/" . $model->id_upload . "/" . $file->name;
							$arquivo->excluido = (int) 0;
							$arquivo->tamanho = $file->size;
							$arquivo->id_upload_fk = $model->id_upload;
							$arquivo->categoria = $model->categoria;
							$arquivo->save();
							$file->saveAs($caminho . "/" . $file);
							chmod($caminho . "/" . $file, 0777);
						}
						
						$link = CHtml::link(Yii::app()->createAbsoluteUrl('site/download/' . $model->id_upload), array('site/download/' . $model->id_upload));
						$msg = 'Upload realizado com Sucesso!<br>Link para download: ' . $link;
						Yii::app()->user->setFlash('success', $msg);
					}
				} else {
					Yii::app()->user->setFlash('error','Arquivo(s) Inválidos!');
				}
			} else {
				Yii::app()->user->setFlash('error','É necessário selecionar ao menos um arquivo!');
			}
		}
		$this->render('novoUpload',array(
			'model'=>$model,
		));
	}
	
	public function actionMeusUploads()
	{
		$model=new Upload;
		$model->unsetAttributes();
		if(isset($_GET['Upload']))
			$model->attributes=$_GET['Upload'];
		$this->render('meusUploads',array(
			'model'=>$model,
		));
	}
	
	public function actionDelete($id)
	{
		$this->loadModel($id)->deletar();
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('meusUploads'));
	}

	public function loadModel($id)
	{
		$model=Upload::model()->findByPk($id);
		if ($model===null || $model->id_usuario_fk != Usuario::getUsuario()->id_usuario)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='upload-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	private function ValidaArquivos($files)
	{
		foreach ($files as $file)
		{
			if ($file->hasError)
			{
				return false;
			}
		}
		return true;
	}
	
	private function CriarPasta($caminho)
	{
		mkdir($caminho);
		chmod($caminho, 0777);
		return true;
	}
}